import sysConfig from "@/config";
import { getToken } from "@/utils/auth";
import errorCode from "@/utils/errorCode";

const timeout = 15000;

const request = (config) => {
  const baseUrl = sysConfig.baseUrl;
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false;
  config.header = config.header || {};
  if (getToken() && !isToken) {
    config.header["Authorization"] = "Bearer " + getToken();
    // config.header["version"] = uni.getSystemInfoSync()?.appWgtVersion;//版本更新设置
  }
  // get请求映射params参数
  if (config.params) {
    let url = config.url + "?" + tansParams(config.params);
    url = url.slice(0, -1);
    config.url = url;
  }
  uni.showLoading({
    title: "加载中...",
    mask: true,
  });
  return new Promise((resolve, reject) => {
    uni
      .request({
        method: config.method || "get",
        timeout: config.timeout || timeout,
        url: config.baseUrl || baseUrl + config.url,
        data: config.data,
        header: config.header,
        dataType: "json",
        sslVerify: false,
      })
      .then((response) => {
        		
if(response.data.code==1){
	uni.showToast({
	  title: response.data.msg,
	  icon: "error",
	});
	reject(response.data.code);
}
        let { error, data } = response;
        if (error) {
          uni.showToast({
            title: "后端接口异常",
            icon: "none",
          });
          reject("后端接口连接异常");
          return;
        }

        const code = data.data.code || 200;
        const msg = errorCode[code] || data.data.msg || errorCode["default"];
        if (code === 401) {
          uni.showModal({
            title: "提示",
            content: "登录状态已过期，您也可以继续留在该页面，或者重新登录?",
            success: (res) => {
              if (res.confirm) {
                uni.reLaunch({ url: "/pages/login" });
              } else if (res.cancel) {
                console.log("用户点击取消");
              }
            },
          });

          reject("无效的会话，或者会话已过期，请重新登录。");
        } else if (code === 500) {
          uni.showToast({
            title: msg,
            icon: "error",
          });

          reject("500");
        } else if (code !== 200) {
          uni.showToast({
            title: msg,
            icon: "error",
          });
          reject(code);
        }
        resolve(data.data);
      })
      .catch((error) => {
        let { msg } = error;

        if (msg === "Network Error") {
          msg = "后端接口连接异常";
        } else if (msg.includes("timeout")) {
          msg = "系统接口请求超时";
        } else if (msg.includes("Request failed with status code")) {
          msg = "系统接口" + msg.substr(msg.length - 3) + "异常";
        }
        uni.showToast({
          title: msg,
          icon: "error",
        });
        reject(error);
      })
      .finally(() => {
        uni.hideLoading();
      });
  });
};

export default request;
